package org.linloong.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author dbo
 */
@Slf4j
@Service
public class ZipUtils {


    public byte[] zipMultipleFiles(List<MultipartFile> files) throws Exception {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ZipOutputStream zos = new ZipOutputStream(bos)){
            for (MultipartFile file : files) {
                if (file.isEmpty()) continue;
                ZipEntry zipEntry = new ZipEntry(file.getOriginalFilename());
                zos.putNextEntry(zipEntry);
                zos.write(file.getBytes());
                zos.closeEntry();
            }
            return bos.toByteArray();
        } catch (Exception e) {
            log.error("文件压缩失败: {}", e.getMessage());
            throw new Exception("文件压缩失败", e);
        }
    }

    public byte[] zipBytes(Map<String, byte[]> map) throws Exception {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ZipOutputStream zos = new ZipOutputStream(bos)){
            for (Map.Entry<String, byte[]> entry : map.entrySet()) {
                ZipEntry zipEntry = new ZipEntry(entry.getKey());
                zos.putNextEntry(zipEntry);
                zos.write(entry.getValue());
                zos.closeEntry();
            }
            return bos.toByteArray();
        } catch (Exception e) {
            log.error("文件压缩失败: {}", e.getMessage());
            throw new Exception("文件压缩失败", e);
        }
    }

    public byte[] zipPaths(List<Path> list) throws Exception {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ZipOutputStream zos = new ZipOutputStream(bos)){
            for (Path path : list) {
                if (!Files.exists(path)) continue;
                ZipEntry zipEntry = new ZipEntry(path.getFileName().toString());
                zos.putNextEntry(zipEntry);
                Files.copy(path, zos);
                zos.closeEntry();
            }
            return bos.toByteArray();
        } catch (Exception e) {
            log.error("文件压缩失败: {}", e.getMessage());
            throw new Exception("文件压缩失败", e);
        }
    }

}
